const ws = require("nodejs-websocket");

const clients = new Set();

const server = ws
    .createServer(function (socket) {
        if (clients.has(socket) == false) {
            clients.add(socket);
        }

        // 事件名称为text(读取字符串时，就叫做text)，读取客户端传来的字符串
        socket.on("text", function (str) {
            //向前端回复消息
            console.log("服务器端收到客户端端发来的消息了！");
            // 在控制台输出前端传来的消息
            console.log(str);
            // socket.sendText(str);
            broadcast(str, socket);
        });

        socket.on("error", function (reason) {
            console.log("Connection error", reason);
            clients.delete(socket);
        });

        socket.on("close", function (code, reason) {
            console.log("Connection closed", code, reason);
            clients.delete(socket);
        });
    })
    .listen(36000);

server.on("error", function (reason) {
    console.log("Server error", reason);
});

function broadcast(msg, socket) {
    for (let client of clients) {
        if (client != socket) {
            client.sendText(msg);
        }
    }
}

// function broadcast(server, msg) {
//     server.connections.forEach(function (conn) {
//         conn.sendText(msg)
//     })
// }
